<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="统计日期" prop="date" :table-form-merge="1.1">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>

      <el-form-item label="销售渠道" prop="num">
        <el-select v-model="query.orderSource" multiple collapse-tags clearable>
          <el-option
            v-for="item in orderSourceOptions"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      :row-key="setRowKey"
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      element-loading-text="加载中"
      :column="column"
      :data="treeTableData"
      custom-column
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { orderStatisticsList, queryMap } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  export default {
    name: 'orderStatistics',
    data() {
      return {
        query: {
          orderSource: '',
          date: []
        },
        orderSourceOptions: [],
        tableData: []
      }
    },
    computed: {
      treeTableData() {
        const treeTableData = []

        const orgMap = {}
        this.tableData.forEach((item) => {
          orgMap[item.orgId] = item
          if (item.parentId > 0) {
            orgMap[item.orgId]._parentId = item.parentId
          }
        })
        this.tableData.forEach((item) => {
          const csmTypeArr = ['', '1', '2', '4']
          let flag = true
          for (let j = 0; j < csmTypeArr.length; j++) {
            const _type =
              csmTypeArr[j] === ''
                ? 'goodsId-' + item.goodsId
                : 'goodsId-' + item.goodsId + '-' + csmTypeArr[j]
            orgMap[item.orgId][_type] = orgMap[item.orgId][_type] || 0
            if (orgMap[item.orgId][_type] === 0) {
              flag = false
            }
            orgMap[item.orgId][_type] += item['gasCount' + csmTypeArr[j]]
          }
          orgMap[item.orgId]['total'] = orgMap[item.orgId]['total'] || 0
          orgMap[item.orgId]['total'] += item.gasCount
          if (item.parentId > 0) {
            for (const _key in item) {
              if (_key.indexOf('goodsId-') > -1) {
                if (orgMap[item.parentId]) {
                  if (!orgMap[item.parentId][_key]) {
                    orgMap[item.parentId][_key] = item[_key]
                  } else {
                    orgMap[item.parentId][_key] += item[_key]
                  }
                  if (_key.split('-').length === 2) {
                    orgMap[item.parentId]['total'] = orgMap[item.parentId]['total'] || 0
                    orgMap[item.parentId]['total'] += item[_key]
                  }
                }
              }
            }
          }
          if (item.parentId === 0 && flag) {
            for (const _key in orgMap[item.orgId]) {
              if (_key.indexOf('goodsId-') > -1) {
                if (_key.split('-')[1] === 0) {
                  continue
                }
                if (item.goodsId === _key.split('-')[1]) {
                  orgMap[item.orgId][_key] += item['gasCount' + (_key.split('-')[2] || '')]
                }
              }
            }
          }
        })
        for (const orgId in orgMap) {
          if (orgMap[orgId].total > 0) {
            treeTableData.push(orgMap[orgId])
          }
        }
        return getTreeData(treeTableData)
      },
      column() {
        const column = [
          {
            prop: 'orgName',
            label: '机构名称',
            width: 200
          }
        ]

        const footerColumn = {
          prop: 'total',
          label: '合计',
          width: 100,
          render: (h, { row }) => <span>{row['total'] === 0 ? '' : row['total']}</span>
        }
        const csmTypeHashMap = {
          居民: '-1',
          商业: '-2',
          工业: '-4',
          小计: ''
        }
        const goodsMap = {}
        this.tableData.forEach((v) => {
          if (v.goodsId > 0 && !goodsMap[v.goodsId]) {
            column.push({
              label: v.gasXH,
              goodsId: v.goodsId,
              goodsCode: v.goodsCode,
              showIndex: v.showIndex || 0,
              children: []
            })
            goodsMap[v.goodsId] = v.goodsId
          }
        })
        column.forEach((v) => {
          if (v.label !== '机构名称') {
            for (const key in csmTypeHashMap) {
              const prop = `goodsId-${v.goodsId}${csmTypeHashMap[key]}`
              // let prop = `gasCount${csmTypeHashMap[key]}`;
              v.children.push({
                label: key,
                align: 'right',
                prop: prop,
                width: 50,
                render: (h, { row }) => <span>{row[prop] === 0 ? '' : row[prop]}</span>
              })
            }
          }
        })
        column.sort((a, b) => {
          if (a.showIndex === 0) {
            a.showIndex = 999999999
          }
          if (b.showIndex === 0) {
            b.showIndex = 999999999
          }
          if (a.showIndex < b.showIndex) {
            return -1
          }
          if (a.showIndex === b.showIndex) {
            if (a.goodsCode < b.goodsCode) {
              return -1
            }
          }
          return 1
        })
        column.push(footerColumn)
        return column
      }
    },
    created() {
      this.queryOptionsMap()
    },
    methods: {
      // 查询枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          queryMap({ enumName: 'OrderSource' })
        // queryMap({ enumName: 'CustomerType' })
        ])

        this.orderSourceOptions = res1.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      setRowKey(row) {
        return `${row.orgId}-${row.gasXH}`
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        // if (this.date && this.date.length === 2) {
        //   query[this.dateType] = moment(this.date[0]).format();
        //   query[`${this.dateType}End`] = moment(this.date[1]).format();
        // }
        const res = await orderStatisticsList(query)
        this.tableData = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped></style>
